<template>
  <div class="calculation-list-container">
    <el-page-header
        content="理算记录管理"
        @back="handleBack"
        class="page-header"
    />

    <el-card shadow="hover" class="main-card">
      <!-- 查询区域 -->
      <el-form :model="searchForm" label-width="120px" class="search-form" inline>
        <el-form-item label="理算状态" prop="calculationStatus">
          <el-select
              v-model="searchForm.calculationStatus"
              placeholder="请选择理算状态"
              clearable
              style="width: 160px"
          >
            <el-option label="全部" value="" />
            <el-option label="已理算" value="1" />
            <el-option label="已复核" value="2" />
            <el-option label="已驳回" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 列表区域 -->
      <el-table
          v-loading="tableLoading"
          :data="tableData"
          border
          stripe
          style="width: 100%; margin-top: 10px"
          @row-hover="handleRowHover"
      >
        <el-table-column
            prop="calculationId"
            label="理算ID"
            align="center"
            min-width="200"
        />
        <el-table-column
            prop="reportNo"
            label="报案号"
            align="center"
            min-width="190"
        />
        <el-table-column
            prop="registrationId"
            label="立案ID"
            align="center"
            min-width="180"
        />
        <el-table-column
            prop="policyId"
            label="保单编号"
            align="center"
            min-width="180"
        />
        <el-table-column
            prop="insuredId"
            label="投保人ID"
            align="center"
            min-width="120"
        />
        <el-table-column
            prop="calculatorName"
            label="理算员"
            align="center"
            min-width="140"
        >
          <template #default="scope">
            <span>{{ scope.row.calculatorName || scope.row.calculatorId }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="calculationTime"
            label="理算时间"
            align="center"
            min-width="180"
        />
        <el-table-column
            prop="sumInsured"
            label="保单总保额(元)"
            align="center"
            min-width="140"
        >
          <template #default="scope">{{ formatCurrency(scope.row.sumInsured) }}</template>
        </el-table-column>
        <el-table-column
            prop="lossRate"
            label="核定损失率(%)"
            align="center"
            min-width="140"
        >
          <template #default="scope">{{ formatRate(scope.row.lossRate) }}</template>
        </el-table-column>
        <el-table-column
            prop="lossAmount"
            label="核定损失金额(元)"
            align="center"
            min-width="140"
        >
          <template #default="scope">{{ formatCurrency(scope.row.lossAmount) }}</template>
        </el-table-column>
        <el-table-column
            prop="calculationStatus"
            label="理算状态"
            align="center"
            min-width="120"
        >
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.calculationStatus)">
              {{ statusMap[scope.row.calculationStatus] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
            min-width="100"
            fixed="right"
        >
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleView(scope.row)"
                icon="el-icon-eye"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
        />
      </div>
    </el-card>

    <!-- 详情弹窗（优化：去除空数据） -->
    <el-dialog
        v-model="detailVisible"
        title="理算记录详情"
        :width="dialogWidth"
        :before-close="handleDialogClose"
        destroy-on-close
    >
      <el-descriptions column="2" border class="detail-descriptions">
        <!-- 理算唯一ID（必展示） -->
        <el-descriptions-item label="理算唯一ID" :span="2" class="highlight-item">
          {{ detailData.calculationId }}
        </el-descriptions-item>

        <!-- 基础关联信息（仅展示有值项） -->
        <el-descriptions-item
            v-if="detailData.reportNo"
            label="报案号"
        >{{ detailData.reportNo }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.registrationId"
            label="立案ID"
        >{{ detailData.registrationId }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.policyId"
            label="保单编号"
        >{{ detailData.policyId }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.insuredId"
            label="投保人ID"
        >{{ detailData.insuredId }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.calculatorId"
            label="理算员ID"
        >{{ detailData.calculatorId }}</el-descriptions-item>

        <!-- 理算员姓名：排除默认提示文本 -->
        <el-descriptions-item
            v-if="detailData.calculatorName && detailData.calculatorName !== '未关联工作人员表'"
            label="理算员姓名"
        >{{ detailData.calculatorName }}</el-descriptions-item>

        <!-- 时间信息（仅展示有值项） -->
        <el-descriptions-item
            v-if="detailData.calculationTime"
            label="理算时间"
        >{{ detailData.calculationTime }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.createTime"
            label="数据创建时间"
        >{{ detailData.createTime }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.updateTime"
            label="最后更新时间"
        >{{ detailData.updateTime }}</el-descriptions-item>

        <!-- 金额计算信息（仅展示有值项） -->
        <el-descriptions-item
            v-if="detailData.sumInsured"
            label="保单总保额(元)"
        >{{ formatCurrency(detailData.sumInsured) }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.lossRate"
            label="核定损失率(%)"
        >{{ formatRate(detailData.lossRate) }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.lossAmount"
            label="核定损失金额(元)"
        >{{ formatCurrency(detailData.lossAmount) }}</el-descriptions-item>

        <!-- 计算逻辑：固定展示 -->
        <el-descriptions-item label="计算逻辑" :span="2">
          <span class="text-primary">核定损失金额 = 保单总保额 × 核定损失率 ÷ 100</span>
        </el-descriptions-item>

        <!-- 状态与说明（仅展示有值项） -->
        <el-descriptions-item
            v-if="detailData.calculationStatus"
            label="理算状态"
        >
          <el-tag :type="getStatusTagType(detailData.calculationStatus)">
            {{ statusMap[detailData.calculationStatus] || detailData.calculationStatus }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.statusUpdateTime"
            label="状态更新时间"
        >{{ detailData.statusUpdateTime }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.calculationBasis"
            label="理算依据"
            :span="2"
        >{{ detailData.calculationBasis }}</el-descriptions-item>

        <el-descriptions-item
            v-if="detailData.calculationRemark"
            label="理算备注"
            :span="2"
        >{{ detailData.calculationRemark }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { Search, Eye } from '@element-plus/icons-vue'
import hxxp from '@/utils/hxxp' // 复用项目中的请求工具

// 路由实例
const router = useRouter()

// ---------------------- 1. 状态映射与常量定义 ----------------------
// 理算状态映射（与后端 AiClaimCalculation 实体类对应）
const statusMap = {
  '1': '已理算',
  '2': '已复核',
  '3': '已驳回'
}

// 状态标签类型映射
const statusTagTypeMap = {
  '1': 'primary',   // 已理算-蓝色
  '2': 'success',   // 已复核-绿色
  '3': 'danger'     // 已驳回-红色
}

// ---------------------- 2. 页面状态与数据 ----------------------
// 加载状态
const tableLoading = ref(false)

// 弹窗状态
const detailVisible = ref(false)

// 弹窗宽度（响应式）
const dialogWidth = computed(() => {
  return window.innerWidth < 768 ? '90%' : '900px'
})

// 搜索表单
const searchForm = reactive({
  calculationId: '',    // 理算ID
  reportNo: '',         // 报案号
  registrationId: '',   // 立案ID
  calculationStatus: '' // 理算状态（1-已理算，2-已复核，3-已驳回）
})

// 分页配置
const pagination = reactive({
  currentPage: 1,  // 当前页（默认1）
  pageSize: 10,    // 每页条数（默认10）
  total: 0         // 总条数（后端返回）
})

// 表格数据
const tableData = ref([])

// 详情弹窗数据
const detailData = ref({})

// ---------------------- 3. 工具函数 ----------------------
/**
 * 格式化金额（保留2位小数）
 */
const formatCurrency = (value) => {
  if (value === null || value === undefined || value === '') return '0.00'
  const num = typeof value === 'string' ? parseFloat(value) : value
  return isNaN(num) ? '0.00' : num.toFixed(2)
}

/**
 * 格式化损失率（保留2位小数，添加%符号）
 */
const formatRate = (value) => {
  if (value === null || value === undefined || value === '') return '0.00%'
  const num = typeof value === 'string' ? parseFloat(value) : value
  return isNaN(num) ? '0.00%' : `${num.toFixed(2)}%`
}

/**
 * 根据状态获取标签类型
 */
const getStatusTagType = (status) => {
  return statusTagTypeMap[status?.toString()] || 'info'
}

// ---------------------- 4. 核心业务逻辑 ----------------------
/**
 * 页面加载时获取理算记录列表
 */
onMounted(() => {
  fetchCalculationList()
})

/**
 * 获取理算记录列表（调用后端接口）
 */
const fetchCalculationList = async () => {
  tableLoading.value = true
  try {
    // 构造查询参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      calculationStatus: searchForm.calculationStatus ? Number(searchForm.calculationStatus) : undefined,
      calculationId: searchForm.calculationId.trim() || undefined,
      reportNo: searchForm.reportNo.trim() || undefined,
      registrationId: searchForm.registrationId.trim() || undefined
    }

    // 调用后端接口
    const response = await hxxp.get('/aiClaimCalculation/CalculationList', { params })
    console.log('理算记录列表查询响应:', response)

    if (response.code === 100200) {
      // 数据映射处理
      tableData.value = response.data.list.map(item => ({
        ...item,
        calculationTime: item.calculationTime ? item.calculationTime.replace('T', ' ') : '-',
        calculationStatus: item.calculationStatus?.toString() || '',
        calculatorName: item.calculatorName || ''
      }))
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取理算记录列表失败')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取理算记录列表异常:', error)
    ElMessage.error(`获取理算记录失败：${error.message || '网络异常'}`)
    tableData.value = []
    pagination.total = 0
  } finally {
    tableLoading.value = false
  }
}

/**
 * 搜索按钮点击事件
 */
const handleSearch = () => {
  pagination.currentPage = 1
  fetchCalculationList()
}

/**
 * 重置按钮点击事件
 */
const handleReset = () => {
  // 清空搜索表单
  searchForm.calculationId = ''
  searchForm.reportNo = ''
  searchForm.registrationId = ''
  searchForm.calculationStatus = ''
  // 重置分页
  pagination.currentPage = 1
  pagination.pageSize = 10
  // 重新获取列表
  fetchCalculationList()
}

/**
 * 分页条数改变事件
 */
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchCalculationList()
}

/**
 * 当前页改变事件
 */
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchCalculationList()
}

/**
 * 查看理算记录详情
 */
const handleView = async (row) => {
  if (!row.calculationId) {
    ElMessage.warning('理算ID缺失，无法查看详情')
    return
  }

  // 显示加载状态
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在加载详情数据...',
    target: document.querySelector('.main-card')
  })

  try {
    // 调用后端详情接口
    const response = await hxxp.get('/aiClaimCalculation/CalculationById', {
      params: { calculationId: row.calculationId }
    })
    console.log('理算记录详情查询响应:', response)

    if (response.code === 100200) {
      const data = response.data
      // 处理详情数据格式（统一空值处理）
      detailData.value = {
        ...data,
        // 时间格式处理
        calculationTime: data.calculationTime ? data.calculationTime.replace('T', ' ') : '',
        createTime: data.createTime ? data.createTime.replace('T', ' ') : '',
        updateTime: data.updateTime ? data.updateTime.replace('T', ' ') : '',
        statusUpdateTime: data.statusUpdateTime ? data.statusUpdateTime.replace('T', ' ') : '',
        // 状态转为字符串
        calculationStatus: data.calculationStatus?.toString() || '',
        // 理算员姓名处理（排除默认提示文本）
        calculatorName: data.calculatorName === '未关联工作人员表' ? '' : (data.calculatorName || ''),
        // 其他字段空值处理
        reportNo: data.reportNo || '',
        registrationId: data.registrationId || '',
        policyId: data.policyId || '',
        insuredId: data.insuredId || '',
        calculatorId: data.calculatorId || '',
        sumInsured: data.sumInsured || 0,
        lossRate: data.lossRate || 0,
        lossAmount: data.lossAmount || 0,
        calculationBasis: data.calculationBasis || '',
        calculationRemark: data.calculationRemark || ''
      }
      // 显示详情弹窗
      detailVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取理算记录详情失败')
    }
  } catch (error) {
    console.error('获取理算记录详情异常:', error)
    ElMessage.error(`获取详情失败：${error.message || '网络异常'}`)
  } finally {
    // 关闭加载状态
    loadingInstance.close()
  }
}

/**
 * 关闭详情弹窗
 */
const handleDialogClose = () => {
  detailVisible.value = false
}

/**
 * 返回上一页
 */
const handleBack = () => {
  router.back()
}

/**
 * 表格行 hover 事件
 */
const handleRowHover = (row, column, rowIndex) => {
  // 行hover高亮效果
}
</script>

<style scoped>
.calculation-list-container {
  padding: 24px;
  max-width: 1800px;
  margin: 0 auto;
  background-color: #fafafa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 20px;
}

.main-card {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

/* 搜索区域样式 */
.search-form {
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

/* 表格区域样式 */
.el-table {
  margin-bottom: 16px;
}

.el-table__row:hover > td {
  background-color: #f0f7ff !important;
}

/* 分页区域样式 */
.pagination-container {
  margin-top: 16px;
  text-align: right;
}

/* 详情弹窗样式 */
.detail-descriptions {
  margin-top: 8px;
}

.highlight-item {
  background-color: #f8f9fa;
  font-weight: 500;
}

.text-primary {
  color: #1890ff;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .calculation-list-container {
    padding: 16px;
  }

  .main-card {
    padding: 16px;
  }

  .search-form {
    flex-direction: column;
    align-items: flex-start !important;
  }

  .el-form-item {
    width: 100% !important;
  }
}

@media (max-width: 768px) {
  .el-descriptions {
    column-count: 1 !important;
  }

  .pagination-container {
    text-align: center;
  }

  .el-table-column {
    min-width: 120px !important;
  }
}
</style>
